using System;
using System.IO;
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using AngleSharp.Io;

static class TestExtensions
{
    public static String GetTagName(this INode node)
    {
        var element = node as IElement;
        return element.LocalName;
    }

    public static IConfiguration WithMockRequester(this IConfiguration config, IRequester mockRequester)
    {
        return config.With(mockRequester).WithDefaultLoader(new LoaderOptions
        {
            IsResourceLoadingEnabled = true,
        });
    }

    public static IDocument ToHtmlDocument(this String sourceCode, IConfiguration configuration = null)
    {
        var context = BrowsingContext.New(configuration ?? Configuration.Default);
        var htmlParser = context.GetService<IHtmlParser>();
        return htmlParser.ParseDocument(sourceCode);
    }

    public static INodeList ToHtmlFragment(this String sourceCode, IElement contextElement = null, IConfiguration configuration = null)
    {
        var context = BrowsingContext.New(configuration);
        var htmlParser = context.GetService<IHtmlParser>();
        return htmlParser.ParseFragment(sourceCode, contextElement);
    }

    public static INodeList ToHtmlFragment(this String sourceCode, String contextElement, IConfiguration configuration = null)
    {
        var doc = String.Empty.ToHtmlDocument();
        var element = doc.CreateElement(contextElement);
        return sourceCode.ToHtmlFragment(element, configuration);
    }

    public static IDocument ToHtmlDocument(this Stream content, IConfiguration configuration = null)
    {
        var context = BrowsingContext.New(configuration);
        var htmlParser = context.GetService<IHtmlParser>();
        return htmlParser.ParseDocument(content);
    }
}